<?php

define('TEST_TABLE_COUNT', 50); // 测试平台分表个数
define('WX_TABLE_COUNT', 200);  // 正式平台分表个数

/**
 * Class SqlAction  正式服务器分表更新sql
 * LLyeap <LL_strive@163.com> 2017-11-15
 *
 * 每一次更新完成后, 需要把函数权限改为private, 防止重复执行
 */
class SqlAction extends Action
{

    public function customInfo($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_mds = 'ALTER TABLE `wx_' . $i . '_user` 
	ADD COLUMN `customInfo` text NULL;
';

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';
        }
    }
    public function updateMediaId($isWx = 1)
    {
        $customer_model = M('customer');
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $customer = $customer_model->alias('c')
                ->join('ind_media_info m on m.cid = c.id and m.uuid = c.uuid')
                ->field('m.id as mediaId')
                ->where(['c.id' => $i])
                ->select();
            if (count($customer) == 1) {
                $mediaId = $customer[0]['mediaId'];
            } else {
                continue;
            }
            if (empty($mediaId)) $mediaId = 0;
            $sql_mds = 'update wx_' . $i . '_user_group_menu set mediaId=' . $mediaId;

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';
        }
    }
    public function addMediaId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_mds = 'ALTER TABLE `wx_'.$i.'_material_keyword` 
	DROP PRIMARY KEY,
	ADD PRIMARY KEY(`id`,`materialId`,`keyword`);
';

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';
        }
    }
    public function addIndex($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_mds = 'ALTER TABLE `wx_'.$i.'_user_weixin_info` ADD INDEX `idx_userId` (`userId`)';

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';
        }
    }
    public function menuMediaId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_mds = 'ALTER TABLE `wx_' . $i . '_user_group_menu` 
	ADD COLUMN `mediaId` int(11) NULL;';

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';
        }
    }

    public function log111($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_mds = 'ALTER TABLE `wx_' . $i . '_log`
	DROP COLUMN `loginName`,
	ADD COLUMN `cid` int(11) NOT NULL COMMENT \'customerId\' AFTER `createTime`,
	ADD COLUMN `cus_user_id` int(11) NULL COMMENT \'wx_customer_user中的id\' AFTER `cid`,
	ADD COLUMN `cus_user_fullName` varchar(64) NULL COMMENT \'wx_customer_user中的fullname\' AFTER `cus_user_id`,
	ADD COLUMN `module_name` varchar(64) NULL COMMENT \'对应的Module_name\' AFTER `cus_user_fullName`,
	ADD COLUMN `content_sql` varchar(255) NULL COMMENT \'记录操作的SQL语句\' AFTER `module_name`;
';

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';
        }
    }

    /**
     * 20171115 - 更新商城首页面和详情页面优化, 创建分表索引
     *
     * 开发: 杰
     * 更新: LLyeap
     */
    private function addInd($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_mds = 'create index mds_idx_isDef_' . $i . ' on wx_' . $i . '_module_distribution_scheme(isDefault)';

            $res_mds = M()->query($sql_mds);
            $sql_mds = M()->getLastSql();
            echo $i . '->' . $res_mds . ' | sql = ' . $sql_mds . '<br />';

            $sql_uatc = 'create index uadc_idx_uName_' . $i . ' on wx_' . $i . '_user_access_tag_count(fromUserName)';
            $res_uatc = M()->query($sql_uatc);
            $sql_uatc = M()->getLastSql();
            echo $i . '->' . $res_uatc . ' | sql = ' . $sql_uatc . '<br />';
            echo '<br />';

        }
    }

    /**
     * 20171201 - 更新营销圈
     *
     * 开发: 杰
     * 更新: LLyeap
     */
    public function adUserCol($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_user`" .
                "ADD COLUMN `mediaId`  int(11) DEFAULT 0 COMMENT '自媒体id' AFTER `expires_in`," .
                "ADD COLUMN `email`  varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '邮箱'," .
                "ADD COLUMN `city`  varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '城市' AFTER `email`," .
                "ADD COLUMN `province`  varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '省份' AFTER `city`," .
                "ADD COLUMN `birthday`  timestamp NULL DEFAULT NULL COMMENT '生日' AFTER `province`;";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

    //数据迁移
    public function dataMigration()
    {
        set_time_limit(0);
        Session::switchCustomer(0);
        $mimallUser = M('mimall_user');
        $quanUser = M('quan_user');

        //取出所有一级推荐人信息
        //$idInfo = $mimallUser->field("id,uId,qId,miUid")->select();
        //进行循环查询处理一级推荐人数据[现在不需要处理]
        // foreach ($idInfo as $key => $value) {
        //     //如果uId和miUid相等则需要去quan_user表里面去查询上一级的推荐人
        //     if ($value['uId'] == $value['miUid']) {
        //         //获得原始的上级推荐人信息
        //         $where_quan['uid'] = $value['uId'];
        //         $where_quan['deleted'] = 0;
        //         $refereeUid = $quanUser->where($where_quan)->getField("refereeUid");

        //         //将推荐人信息存入到mimall_user表中新加一级推荐人字段
        //         $mimallUser->where("id=" . $value['id'])->setField("refereeUid", $refereeUid);

        //     } else {
        //         //直接将推荐人信息存入到mimall_user表中新加一级推荐人字段
        //         $mimallUser->where("id=" . $value['id'])->setField("refereeUid", $value['miUid']);
        //     }

        // }

        //取出所有二级推荐人信息
        $preInfo = $mimallUser->field("id,qId,miUid")->where("miUid IS NOT NULL")->select();
        //进行循环查询处理二级推荐人数据
        foreach ($preInfo as $key => $value) {
            //去quan_user表里面去查询上一级的推荐人
            $where_quan['uid'] = $value['miUid'];
            $where_quan['qid'] = $value['qId'];
            $where_quan['deleted'] = 0;
            $refereeUid = $quanUser->where($where_quan)->getField("refereeUid");

            //将推荐人信息存入到mimall_user表中新加二级推荐人字段
            $mimallUser->where("id=" . $value['id'])->setField("refereeUid", $refereeUid);

        }

        //取出所有三级推荐人信息
        $prePreInfo = $mimallUser->field("id,qId,refereeUid")->where("refereeUid IS NOT NULL")->select();
        //进行循环查询处理二级推荐人数据
        foreach ($prePreInfo as $key => $value) {
            //去quan_user表里面去查询上一级的推荐人
            $where_quan['uid'] = $value['refereeUid'];
            $where_quan['qid'] = $value['qId'];
            $where_quan['deleted'] = 0;
            $preRefereeUid = $quanUser->where($where_quan)->getField("refereeUid");

            //将推荐人信息存入到mimall_user表中新加二级推荐人字段
            $mimallUser->where("id=" . $value['id'])->setField("preRefereeUid", $preRefereeUid);

        }

    }

    /**
     * 20171201 - 分表分享uv统计数据迁移mishare表
     *
     * 开发: LP
     * 更新: LLyeap
     */
    public function mishare()
    {


        Session::switchCustomer(0);
        $MialoadModel = M("mishare");
        $customer = M('customer');


        //注意：去除2个cid之后的所有分表，一个是超级管理员的cid为18，【正式平台为1】。第二个是稿稿的cid为3。
        $where['role'] = array("eq", 'C');
        $cid = $customer->where($where)->getField('id', true);

        foreach ($cid as $v) {
            $mall = M()->query("select * from wx_" . $v . "_share_statistics where module='mall'");
            if (!empty($mall)) {
                foreach ($mall as $value) {
                    $module = $MialoadModel->where(['module' => $value['module'], 'moduleId' => $value['moduleId'], 'cid' => $v])->find();
                    if (empty($module)) {
                        $MialoadModel->create();
                        $MialoadModel->module = $value['module'];
                        $MialoadModel->moduleId = $value['moduleId'];
                        $MialoadModel->createTime = $value['createTime'];
                        $MialoadModel->viewUv = $value['uv'];
                        $MialoadModel->viewCount = $value['uv'];
                        $MialoadModel->cid = $v;
                        $MialoadModel->add();
                    }
                }
            }
        }
    }

    /**
     * 20171201 - 密友信息添加到密友统计
     *
     * 开发: LP
     * 更新: LLyeap
     */
    public function miUStatistics()
    {
        Session::switchCustomer(0);
        $quan_user = M("quan_user");
        $miu_statistics = M("miu_statistics");
        $miU = $quan_user->alias('a')->where(['a.deleted' => 0])->join("wx_miyouquan as b On a.qid=b.id")->field('a.uid,b.cid')->select();
        foreach ($miU as $v) {
            $miUInfo = $miu_statistics->where(['uid' => $v['uid'], 'cid' => $v['cid']])->find();
            if (empty($miUInfo)) {
                $miu_statistics->create();
                $miu_statistics->uid = $v['uid'];
                $miu_statistics->cid = $v['cid'];
                $miu_statistics->add();
            }
        }
    }

    /**
     * 20171201 - 销售源信息添加到密友统计
     *
     * 开发: LP
     * 更新: LLyeap
     */
    public function saleSourceStatistics()
    {
        Session::switchCustomer(0);
        $quan_user = M("quan_user");
        $salesource_statistics = M("salesource_statistics");
//        $where['saleSource'] = array('neq', NULL);
        $miU = $quan_user->alias('a')->join("wx_miyouquan as b On a.qid=b.id")->field('a.saleSource as uid,b.cid')->select();
        foreach ($miU as $v) {
            $miUInfo = $salesource_statistics->where(['uid' => $v['uid'], 'cid' => $v['cid']])->find();
            if (empty($miUInfo) && !empty($v['uid'])) {
                $salesource_statistics->create();
                $salesource_statistics->uid = $v['uid'];
                $salesource_statistics->cid = $v['cid'];
                $salesource_statistics->add();
            }
        }
    }

    /**
     * 20171201 - 密友圈添加到密友圈统计
     *
     * 开发: LP
     * 更新: LLyeap
     */
    public function miyouquStatistics()
    {
        Session::switchCustomer(0);
        $miyouquan = M("miyouquan");
        $miyouquan_statistics = M("miyouquan_statistics");
        $miyouquan = $miyouquan->select();
        foreach ($miyouquan as $v) {
            $myqInfo = $miyouquan_statistics->where(['qid' => $v['id']])->find();
            if (empty($myqInfo)) {
                $data['qid'] = $v['id'];
                $data['cid'] = $v['cId'];
                $miyouquan_statistics->add($data);
            }
        }
    }

    /**
     * 20171201 - 普通用户
     *
     * 开发: LP
     * 更新: LLyeap
     */
    public function userStatistics()
    {
        Session::switchCustomer(0);
        $customer = M('customer');
        $user_statistics = M('user_statistics');


        //注意：去除2个cid之后的所有分表，一个是超级管理员的cid为18，【正式平台为1】。第二个是稿稿的cid为3。
        $where['role'] = array("eq", 'C');
        $cid = $customer->where($where)->getField('id', true);

        foreach ($cid as $v) {
            $user = M()->query("select * from wx_" . $v . "_user");
            if (!empty($user)) {
                foreach ($user as $value) {
                    $module = $user_statistics->where(['cid' => $v, 'uid' => $value['id']])->find();
                    if (empty($module)) {
                        $user_statistics->create();
                        $user_statistics->uid = $value['id'];
                        $user_statistics->cid = $v;
                        $user_statistics->add();
                    }
                }
            }
        }
    }

    /**
     * 20171207 - user表增加二维码url
     *
     * 开发: 孟慧
     * 更新: LLyeap
     */
    public function addQrcodeUrlToUser($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_user`" .
                "ADD COLUMN `qrcodeUrl` varchar(255) NULL COMMENT '二维码图片url';";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

    /**
     * 20171231 - 原文章表标签增加默认分组id
     *
     * 开发: 刘鹏
     * 更新: LLyeap
     */
    public function miContentTagToGroup()
    {
        Session::switchCustomer(0);
        $micontentTagModel = M("micontent_tag");
        $micontentTagGroupModel = M("micontent_tag_group");
        $fromCustomerIds = $micontentTagModel->getField('fromCustomerId', true);
        $cids = array_unique($fromCustomerIds);
        foreach ($cids as $cid) {
            $data['cid'] = $cid;
            $data['groupName'] = '默认';
            $data['createTime'] = date('Y-m-d');
            $data['deleted'] = 0;
            $groupId = $micontentTagGroupModel->add($data);
            $micontentTagModel->where(['fromCustomerId' => $cid])->setField('groupId', $groupId);
        }
    }


    /**
     * 20180102 - mimall_user表推荐人数据迁移
     *
     * 开发: 孟慧
     * 更新:
     */
    public function refereeUidMigration()
    {
        //将原来的二级推荐人信息更改到一级推荐人上
        $two_sql = 'UPDATE wx_mimall_user SET refereeUid=preRefereeUid WHERE uId <> miUid';
        $res_two_sql = M()->query($two_sql);
        //将原来的三级推荐人信息更改到二级推荐人上
        $three_sql = 'UPDATE wx_mimall_user SET preRefereeUid=prePreRefereeUid WHERE uId <> miUid';
        $res_three_sql = M()->query($three_sql);
    }

    public function payPassword($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_user`" .
                "ADD COLUMN `payPassword` varchar(64) NULL COMMENT '支付密码';";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();
            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }


    /**
     * 20171115 - 更新商城首页面和详情页面优化, 创建分表索引
     *
     * 开发: LP
     * 更新:
     */
    public function addMallToField($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_module_mall_store`
  ADD COLUMN `qrcodeBack` varchar(255) DEFAULT NULL COMMENT '用户推广二维码背景',
  ADD COLUMN `qrcodeLocation` varchar(32) DEFAULT NULL COMMENT '二维码在背景上的位置以二维码中心为主(X|Y)',
  ADD COLUMN `qrcodeSize` varchar(32) DEFAULT NULL COMMENT '二维码大小(X*Y)',
  ADD COLUMN `mallHue` tinyint(4) DEFAULT '0' COMMENT '0默认1蓝色',
  ADD COLUMN `isLogin` tinyint(4) DEFAULT NULL COMMENT '是否开启账号密码登录',
  ADD COLUMN `isPhoneLogin` tinyint(4) DEFAULT NULL COMMENT '是否开启手机号登录',
  ADD COLUMN `isVerifyPhone` tinyint(4) DEFAULT NULL COMMENT '是否验证手机号';";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

    /**
     * 20171115 - 更新用户信息字段
     *
     * 开发: LP
     * 更新:
     */
    public function addUserToField($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_user`
  ADD COLUMN `rural` varchar(64) NULL COMMENT '用户唯一标识' AFTER `qrcodeUrl`,
  ADD COLUMN `town` varchar(64) NULL COMMENT '用户唯一标识' AFTER `rural`,
  ADD COLUMN `county` varchar(64) NULL COMMENT '用户唯一标识' AFTER `town`,
  ADD COLUMN `token` varchar(64) NULL COMMENT '用户唯一标识' AFTER `county`,
  ADD COLUMN `expired` datetime NULL COMMENT 'token失效时间' AFTER `token`,
  ADD COLUMN `sex` tinyint(4) NULL COMMENT '性别' AFTER `expired`,
  ADD COLUMN `bankAccount` text NULL COMMENT '银行账户信息' AFTER `sex`,
  ADD COLUMN `address` varchar(255) NULL COMMENT '详细地址' AFTER `bankAccount`;
  ADD COLUMN `isVerifyPhone` tinyint(4) NULL DEFAULT 0 COMMENT '是否通过手机号验证' AFTER `address`;";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }


    /**
     * 20171115 - 更新收货地址信息字段
     *
     * 开发: LP
     * 更新:
     */
    public function addAddressToField($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_user_receiver_address`
  ADD COLUMN `uid` int(11) NULL COMMENT '用户id' AFTER `isAcitivity`;";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

    /**
     * 20171115 - 更新用户详情信息字段
     *
     * 开发: LP
     * 更新:
     */
    public function addUserInfoToField($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_user_info`
  MODIFY COLUMN `fromUserName` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'weixin Open ID' AFTER `id`,
  ADD COLUMN `uid` int(11) NULL COMMENT '用户id' AFTER `lastAddressId`";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

    /**
     * 20170129 - openId查询uid并存储-收货地址
     *
     * 开发: LP
     * 更新:
     */
    public function addressOpenIdToUId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sqlOne = "select * from wx_" . $i . "_user_receiver_address";
            $arr = M()->query($sqlOne);
            if (!empty($arr)) {
                foreach ($arr as $key => $value) {
                    if (!$value['uid']) {
                        $userName = $value['userName'];
                        $sqlTwo = "select id from wx_" . $i . "_user where userName='$userName' limit 1";
                        $userId = M()->query($sqlTwo);
                        $uid = $userId[0]['id'];
                        $sqlThree = "update  wx_" . $i . "_user_receiver_address set uid=$uid where userName='$userName'";
                        M()->query($sqlThree);
                    }
                }
            }
        }
    }


    /**
     * 20170129 - openId查询uid并存储-优惠卷
     *
     * 开发: LP
     * 更新:
     */
    public function couponOpenIdToUId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;
        $sqlOne = "select userId,openid,cId from wx_module_user_coupon where userId=0";
        $arr = M()->query($sqlOne);
        if (!empty($arr)) {
            foreach ($arr as $key => $value) {
                if (!$value['userId']) {
                    $userName = $value['openid'];
                    $sqlTwo = "select id from wx_" . $value['cId'] . "_user where userName='$userName' limit 1";
                    Log::write('LPLPSql:' . $sqlTwo);

                    $userId = M()->query($sqlTwo);
                    $uid = $userId[0]['id'];
                    $sqlThree = "update  wx_module_user_coupon set userId=$uid where openid='$userName'";
                    M()->query($sqlThree);
                }
            }
        }
    }


    /**
     * 20170129 - openId查询uid并存储-用户信息
     *
     * 开发: LP
     * 更新:
     */
    public function userInfoToUId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;
        for ($i = 1; $i < $count; $i++) {
            $sqlOne = "select * from wx_" . $i . "_user_info";
            $arr = M()->query($sqlOne);
            if (!empty($arr)) {
                foreach ($arr as $key => $value) {
                    if (!$value['uid']) {
                        $userName = $value['fromUserName'];
                        $sqlTwo = "select id from wx_" . $i . "_user where userName='$userName' limit 1";
                        $userId = M()->query($sqlTwo);
                        $uid = $userId[0]['id'];
                        $sqlThree = "update  wx_" . $i . "_user_info set uid=$uid where fromUserName='$userName'";
                        M()->query($sqlThree);
                    }
                }
            }
        }
    }


    /**
     * 20170129 - openId查询uid并存储-收藏及收藏历史
     *
     * 开发: LP
     * 更新:
     */
    public function favoriteOpenIdToUId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;
        Session::switchCustomer(0);
        $favoriteModel = M("module_product_favorite");
        for ($i = 1; $i < $count; $i++) {
            $arr = $favoriteModel->select();
            foreach ($arr as $key => $value) {
                if (!$value['uid']) {
                    $userName = $value['fromUserName'];
                    $sqlTwo = "select id from wx_" . $value['fromCustomerId'] . "_user where userName='$userName' limit 1";
                    $userId = M()->query($sqlTwo);
                    $uid = $userId[0]['id'];
                    $favoriteModel->where(['id' => $value['id']])->setField('uid', $uid);
                }
            }
        }
    }


    /**
     * 20170129 - openId查询uid并存储-收藏历史
     *
     * 开发: LP
     * 更新:
     */
    public function favoriteHistroyOpenIdToUId($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;
        Session::switchCustomer(0);
        $favoriteHModel = M("module_product_favorite_histroy");
        for ($i = 1; $i < $count; $i++) {
            $arr = $favoriteHModel->select();
            foreach ($arr as $key => $value) {
                if (!$value['uid']) {
                    $userName = $value['fromUserName'];
                    $sqlTwo = "select id from wx_" . $value['fromCustomerId'] . "_user where userName='$userName' limit 1";
                    $userId = M()->query($sqlTwo);
                    $uid = $userId[0]['id'];
                    $favoriteHModel->where(['id' => $value['id']])->setField('uid', $uid);
                }
            }
        }
    }

    /**
     * 20170129 - openId查询uid并存储-订单详情
     *
     * 开发: LP
     * 更新:
     */
    public function orderDetailOpenIdToUId()
    {
        Session::switchCustomer(0);
        $orderDetailModel = M("module_product_order_detail");
        $productModel = M("module_product");
        $formModel = M("module_product_order_detail");
        $arr = $orderDetailModel->field('id,fromUserName,type,pid,userId')->select();
        foreach ($arr as $key => $value) {
            if (empty($value['userId'])) {
                if ($value['type'] == 'form') {
                    $cid = $formModel->where(['id' => $value['pid']])->getField('cid');
                } else {
                    $cid = $productModel->where(['id' => $value['pid']])->getField('fromCustomerId');
                }
                if (!empty($value['fromUserName'])) {
                    $userName = $value['fromUserName'];
                    $sql = "select * from wx_" . $cid . "_user where userName='$userName'";
                    $userId = M()->query($sql);
                    $uid = $userId[0]['id'];
                    if (!empty($uid)) {
                        $orderDetailModel->where(['id' => $value['id']])->setField('userId', $uid);
                    }
                }
            }
        }
    }


    /**
     * 20170129 - 修改商城设置字段
     *
     * 开发: LP
     * 更新:
     */
    public function mallSaveField($isWx = 1)
    {
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "ALTER TABLE `wx_" . $i . "_module_mall_store`
	CHANGE COLUMN `isLogin` `isUserNameLogin` tinyint(4) NULL COMMENT '是否开启账号密码登录' AFTER `mallHue`;
";

            $res_addCol = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();

            header("Content-type: text/html; charset=utf-8");
            echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }


    /**
     * 20170209 - 根据openId更新用户关注状态
     *
     * 开发: LP
     * 更新:
     */
    public function userSaveStatus()
    {
        $status = USER_STATUS_SUBSCRIBE;
        /* 1.查询授权用户信息*/
        $sql = "select id,userName from wx_114_user where status='sharesubscribe'";
        $user = M()->query($sql);
        foreach ($user as $k => $v) {
            /* 2.查询授权的用户是否关注了公众号*/
            $userInfo = WeixinApi::getUserInfo($v['userName']);
            /* 3.判断是否关注了*/
            if ($userInfo) {
                $id = $v['id'];
                $userName = $v['userName'];
                /* 4.更新用户状态为关注*/
                $sqlSave = "update wx_114_user set status='$status' where id=$id and userName='$userName'";
                M()->query($sqlSave);
                echo $sqlSave;
            }
        }
    }

    /**
     * 20170419 - nmp角色对应权限数据初始化
     *
     * 开发: LP
     * 更新:
     */
    public function role()
    {
        Session::switchCustomer(0);
        $customerModel = M("customer");
        $customerUserModel = M("customer_user");
        $agentInfo = $customerUserModel->where(['agent' => 'agent'])->field('id,customerId')->find();
        $agentCid = $agentInfo['customerId'];
        $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($agentCid, 'agent', '超级管理员', '0', '1', '')";
        M()->execute($sql);
        $arr = M()->getLastInsID();
        log::write('agent-' . $agentCid . '-' . M()->getLastSql());

        $cids = $customerModel->getField('id', true);
        foreach ($cids as $v) {
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'vendor', '商家', '1', '1', '')";
            $vendorId = M()->execute($sql);
            $vendorId = M()->getLastInsID();
            log::write('vendor-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '262', $vendorId),($v, '263', $vendorId),($v, '264', $vendorId),($v, '265', $vendorId),($v, '266', $vendorId),
($v, '259', $vendorId),($v, '260', $vendorId),($v, '146', $vendorId),($v, '136', $vendorId),($v, '138', $vendorId);";
            M()->query($sql1);
            log::write('vendor-role' . $v . '-' . M()->getLastSql());


            /*---系统管理员----*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'business', '系统管理员', '0', '1', '')";
            $businessId = M()->execute($sql);
            $businessId = M()->getLastInsID();
            log::write('business-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '139', $businessId),($v, '225', $businessId),($v, '130', $businessId),($v, '123', $businessId),
($v, '259', $businessId),($v, '260', $businessId),
($v, '125', $businessId),($v, '233', $businessId),($v, '250', $businessId),($v, '255', $businessId),
($v, '256', $businessId),($v, '276', $businessId),($v, '251', $businessId),
($v, '239', $businessId),($v, '240', $businessId),($v, '245', $businessId),($v, '247', $businessId),
($v, '138', $businessId),($v, '136', $businessId),($v, '146', $businessId),
($v, '237', $businessId),
($v, '234', $businessId),($v, '257', $businessId),($v, '246', $businessId),($v, '262', $businessId),($v, '263', $businessId),($v, '265', $businessId),($v, '267', $businessId),($v, '268', $businessId),($v, '269', $businessId);";
            M()->query($sql1);
            log::write('business-role' . $v . '-' . M()->getLastSql());


            /*---运营管理员----*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'operationCenterAdmin', '运营中心管理员', '1', '0', '')";
            $operationCenterAdminId = M()->execute($sql);
            $operationCenterAdminId = M()->getLastInsID();
            log::write('operationCenterAdmin-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '262', $operationCenterAdminId),($v, '263', $operationCenterAdminId),($v, '267', $operationCenterAdminId),($v, '268', $operationCenterAdminId),($v, '269', $operationCenterAdminId),($v, '257', $operationCenterAdminId),($v, '265', $operationCenterAdminId),
($v, '146', $operationCenterAdminId),($v, '136', $operationCenterAdminId),($v, '138', $operationCenterAdminId);";
            M()->query($sql1);
            log::write('operationCenterAdmin-role' . $v . '-' . M()->getLastSql());


            /*---营销管理员----*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'marketCenterAdmin', '营销中心管理员', '1', '0', '')";
            $marketCenterAdminnId = M()->execute($sql);
            $marketCenterAdminnId = M()->getLastInsID();
            log::write('marketCenterAdmin-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '125', $marketCenterAdminnId),($v, '233', $marketCenterAdminnId),($v, '250', $marketCenterAdminnId),($v, '255', $marketCenterAdminnId),
($v, '146', $marketCenterAdminnId),($v, '136', $marketCenterAdminnId),($v, '138', $marketCenterAdminnId);";
            M()->query($sql1);
            log::write('marketCenterAdmin-role' . $v . '-' . M()->getLastSql());

            /*---客户中心管理员----*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'clientCenterAdmin', '客户中心管理员', '1', '0', '')";
            $clientCenterAdminId = M()->execute($sql);
            $clientCenterAdminId = M()->getLastInsID();
            log::write('clientCenterAdmin-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '256', $clientCenterAdminId),($v, '276', $clientCenterAdminId),($v, '251', $clientCenterAdminId),
($v, '146', $clientCenterAdminId),($v, '136', $clientCenterAdminId),($v, '138', $clientCenterAdminId);";
            M()->query($sql1);
            log::write('clientCenterAdmin-role' . $v . '-' . M()->getLastSql());


            /*---内容中心管理员----*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'contentCenterAdmin', '内容中心管理员', '1', '0', '')";
            $contentCenterAdminId = M()->execute($sql);
            $contentCenterAdminId = M()->getLastInsID();
            log::write('clientCenterAdmin-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '239', $contentCenterAdminId),($v, '240', $contentCenterAdminId),($v, '245', $contentCenterAdminId),($v, '247', $contentCenterAdminId),
($v, '146', $contentCenterAdminId),($v, '136', $contentCenterAdminId),($v, '138', $contentCenterAdminId);";
            M()->query($sql1);
            log::write('clientCenterAdmin-role' . $v . '-' . M()->getLastSql());


            /*---商家管理员(未开发该功能)---*/
//            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
//                    ($v, 'newMivendorAdmin', '商家管理员', '1', '0', '')";
//            $contentCenterAdminId = M()->query($sql);
//            log::write('clientCenterAdmin-'.$v.'-'.M()->getLastSql());

            /*---订单中心管理员---*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'orderInfoAdmin', '订单中心管理员', '1', '0', '')";
            $orderInfoAdminId = M()->execute($sql);
            $orderInfoAdminId = M()->getLastInsID();
            log::write('orderInfoAdmin-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '237', $orderInfoAdminId),($v, '146', $orderInfoAdminId),($v, '136', $orderInfoAdminId),($v, '138', $orderInfoAdminId);";
            M()->query($sql1);
            log::write('orderInfoAdmin-role' . $v . '-' . M()->getLastSql());


            /*---结算中心管理员----*/
            $sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'newSettlementAdmin', '结算中心管理员', '1', '0', '')";
            $newSettlementAdminId = M()->execute($sql);
            $newSettlementAdminId = M()->getLastInsID();
            log::write('newSettlementAdmin-' . $v . '-' . M()->getLastSql());
            $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '259', $newSettlementAdminId),($v, '260', $newSettlementAdminId),($v, '146', $newSettlementAdminId),($v, '136', $newSettlementAdminId),($v, '138', $newSettlementAdminId);";
            M()->query($sql1);
            log::write('newSettlementAdmin-role' . $v . '-' . M()->getLastSql());


        }
    }

    /**
     * 20170419 - nmp老平台business,vendor赋予角色数据迁移
     *
     * 开发: LP
     * 更新:
     */
    public function customerRole()
    {
        $arr = ['business', 'vendor'];
        $arr = implode(',', $arr);
        $customerUserModel = M("customer_user");
        $customerUserRoleModel = M("customer_user_role");
        $roleModel = M("role");
        $where['agent'] = array('in', $arr);
        $userInfo = $customerUserModel->where($where)->field('id,customerId,agent')->select();
        foreach ($userInfo as $v) {
            $cid = $v['customerId'];
            $agent = $v['agent'];
            $userId = $v['id'];
            $roleId = $roleModel->where(['cid' => $cid, 'englishRole' => $agent])->getField('id');
            log::write('customerRole' . $v['customerId'] . '-' . $v['id'] . '-' . $roleModel->getLastSql());
            $data['roleId'] = $roleId;
            $data['cid'] = $cid;
            $data['userId'] = $userId;
            $customerUserRoleModel->add($data);
            log::write('customerRole' . $v['customerId'] . '-' . $v['id'] . '-' . $roleModel->getLastSql());
        }
    }

    /**
     * 20170419 - nmp老平台business,vendor赋予角色数据迁移
     *
     * 开发: LP
     * 更新:
     */
    public function vendorRole()
    {
        $roleModel = M("role");
        $where['englishRole'] = array('eq', 'vendor');
        $userInfo = $roleModel->where($where)->field('id,cid')->select();
        foreach ($userInfo as $v) {
            $cid = $v['cid'];
            $roleId = $v['id'];
            $sql = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($cid, '20', $roleId),($cid, '80', $roleId),($cid, '84', $roleId);";
            M()->query($sql);
        }
    }


    /**
     * 20180427 - 在user分表中添加JPUSHRegistrationID,极光推送设备ID字段
     *
     * 开发: mh
     * 更新: mh
     */
       public function userSaveRegistrationID($isWx = 1)
      {
          $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;

          for ($i = 1; $i < $count; $i++) {
              $sql_addCol = "ALTER TABLE `wx_".$i."_user`
ADD COLUMN `JPUSHRegistrationID`  varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '极光推动设备registrationID' AFTER `payPassword`;

";
              $res_addCol = M()->query($sql_addCol);
              $lastSql_addCol = M()->getLastSql();

              header("Content-type: text/html; charset=utf-8");
              echo $i . '->' . $res_addCol . ' | sql = ' . $lastSql_addCol . '<br />';
              echo '<br />';
          }
      }
      public function statisFriendNums(){
          Session::switchCustomer(0);
          $quan_user = M('quan_user');
          $miyouquan_statistics = M('miyouquan');
          $mimall_user = M('mimall_user');
          $miu_statistics = M('miu_statistics');
          $quanIds = $miyouquan_statistics->getField('id',true);
          foreach($quanIds as $v){
              $count = $quan_user->where(['qid' => $v,'deleted' => 0])->count();
              $miyouquan_statistics->where(['id' => $v])->setField('miUCount',$count);
          }




          $miU_where['a.deleted'] = array('eq', 0);
          $miUArr = $quan_user
              ->alias('a')
              ->where($miU_where)
              ->join('wx_miyouquan as b on a.qid=b.id')
              ->field('a.uid,a.qid,b.cId as cid')
              ->select();
          foreach($miUArr as $value){
              $three_miu = $mimall_user->where(['uId' => $value['uid'], 'qId' => $value['qid'], 'cId' => $value['cid']])->find();
              if(!empty($three_miu['refereeUid'])){
                  $resuft = $this->checkMiU($three_miu['refereeUid'],$three_miu['cId']);
                  if($resuft){
                      $data['uid'] = $three_miu['refereeUid'];
                      $data['cid'] = $three_miu['cId'];
                      $miu_statistics->add($data);
                  }
                  $miu_statistics->where(['uid' => $three_miu['refereeUid'],'cid' =>$three_miu['cId']])->setInc('miUCount');
              }
              if(!empty($three_miu['preRefereeUid'])){
                  $resuft = $this->checkMiU($three_miu['preRefereeUid'],$three_miu['cId']);
                  if($resuft){
                      $data['uid'] = $value['preRefereeUid'];
                      $data['cid'] = $value['cid'];
                      $miu_statistics->add($data);
                  }
                  $miu_statistics->where(['uid' => $three_miu['preRefereeUid'],'cid' =>$three_miu['cId']])->setInc('miUCount');
              }
          }

          //普通好友
          $quan_user = $quan_user->alias("mi")->where(['deleted' => 0])->join('wx_miyouquan as qu on mi.qid=qu.id')->field('cid,qid,uid')->select();
          foreach($quan_user as $value){
              if($value['qid'] && $value['cid'] && $value['uid']){
                  $where_friends['mi.miUid'] = $value['uid'];
                  $where_friends['mi.refereeUid'] = $value['uid'];
                  $where_friends['mi.preRefereeUid'] = $value['uid'];
                  $where_friends['_logic'] = "OR";
                  $where_friend["_complex"] = $where_friends;
                  $where_friend["mi.qId"] = $value['qid'];
                  $where_friend["mi.uId"] = array('neq', $value['uid']);
                  $where_friend["mi.cId"] = $value['cid'];


                  $friendCount = $mimall_user->alias("mi")
                      ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$value['qid']." and qu.deleted=0")
                      ->where($where_friend)
                      ->count();
                  $resuft = $this->checkMiU($value['uid'],$value['cid']);
                  if($resuft){
                      $data['uid'] = $value['uid'];
                      $data['cid'] = $value['cid'];
                      $miu_statistics->add($data);
                  }
                  $miu_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setField('friendCount',$friendCount);
              }
          }
      }
      public function statisFriendNums2(){
          Session::switchCustomer(0);
          $quan_user = M('quan_user');
          $miyouquan_statistics = M('miyouquan');
          $mimall_user = M('mimall_user');
          $saleSource_statistics = M('salesource_statistics');
          $miU_where['a.deleted'] = array('eq', 0);
          $miU_where['a.saleSource'] = array('neq', '');
          $miUArr = $quan_user
              ->alias('a')
              ->where($miU_where)
              ->join('wx_miyouquan as b on a.qid=b.id')
              ->group('cId,saleSource')
              ->field('a.saleSource as uid,count(*) as miUCount,b.cId as cid')
              ->select();
          foreach($miUArr as $value){
              if(!empty($value['uid'])){
                  $resuft = $this->checkSaleSource($value['uid'],$value['cid']);
                  if($resuft){
                      $data['uid'] = $value['uid'];
                      $data['cid'] = $value['cid'];
                      $saleSource_statistics->add($data);
                  }
                  $value['miUCount'] = $value['miUCount'] -1;
                  $saleSource_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setField('miUCount',$value['miUCount']);
              }
          }

          //注册好友
          $quanSale = $quan_user->alias("mi")->where(['mi.deleted' => 0,'mi.isSaleSource'=>1])->join('wx_miyouquan as qu on mi.qid=qu.id')->field('cid,qid,uid')->select();
          foreach($quanSale as $value){
              if($value['qid'] && $value['cid'] && $value['uid']){
                  $where_friend["mi.qId"] = $value['qid'];
                  $where_friend["mi.uId"] = array('neq', $value['uid']);
                  $where_friend["mi.cId"] = $value['cid'];
                  $where_friend['mi.saleSource'] = $value['uid'];
                  $friendCount = $mimall_user->alias("mi")
                      ->join("wx_quan_user qu on mi.uId = qu.uid and qu.qid =".$value['qid']." and qu.deleted=0")
                      ->where($where_friend)
                      ->count();
                  $resuft = $this->checkSaleSource($value['uid'],$value['cid']);
                  if($resuft){
                      $data['uid'] = $value['uid'];
                      $data['cid'] = $value['cid'];
                      $saleSource_statistics->add($data);
                  }
                  $saleSource_statistics->where(['uid' => $value['uid'],'cid' =>$value['cid']])->setField('friendCount',$friendCount);
              }
          }
      }
    //检查密友是否存在
    public function checkMiU($uid,$cid){
        Session::switchCustomer(0);
        $miu_statistics = M('miu_statistics');
        $user = $miu_statistics->where(['uid' => $uid, 'cid'=> $cid])->find();
        if(empty($user)){
            return true;
        }
        return false;
    }
    //检查销售源是否存在
    public function checkSaleSource($uid,$cid){
        Session::switchCustomer(0);
        $salesource_statistics = M('salesource_statistics');
        $user = $salesource_statistics->where(['uid' => $uid, 'cid'=> $cid])->find();
        if(empty($user)){
            return true;
        }
        return false;
    }

    public function shareNum(){
        Session::switchCustomer(0);
        $mishare_from = M('mishare_from');
        $user_statistics = M("user_statistics");
        $miu_statistics = M("miu_statistics");
        $salesource_statistics = M("salesource_statistics");
        $quan_user = M("quan_user");
        $arr = $mishare_from -> field('id,uId,count(*) as shareCount,cid')->group('cid,uId')->select();
        log::write('分享信息:'.json_encode($arr));
        foreach ($arr as $key=>$value){
            $uid = $value['uId'];
            $id = $value['id'];
            $cid = $value['cid'];
            $shareCount = $value['shareCount'];
            if ($uid) {
                $result = R("StatisTics/checkUser", array($uid, $cid));
                if ($result) {
                    $statiInfo['uid'] = $uid;
                    $statiInfo['cid'] = $cid;
                    $user_statistics->add($statiInfo);
                }
                $user_statistics->where(['cid' => $cid, 'uid' => $uid])->setField('shareCount',$shareCount);
                log::write('普通用户分享详情_'.$id.':'.$user_statistics->getLastSql());
            }
            //查询是否为注册好友,如果为注册好友 则给分享人注册好友身份分享数量+1
            $where['b.cId'] = array('eq', $cid);
            $where['a.uId'] = array('eq', $uid);
            $where['a.deleted'] = array('eq', 0);
            $userInfo = $quan_user->alias('a')->where($where)->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
            if (!empty($userInfo['qid']) && $uid) {
                $result = R("StatisTics/checkMiU", array($uid, $cid));
                if ($result) {
                    $data['uid'] = $uid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                /** 5.添加密友分享总次数*/
                $miu_statistics->where(['uid' => $uid, 'cid' => $cid])->setField('shareCount',$shareCount);
                log::write('注册好友分享详情_'.$id.':'.$miu_statistics->getLastSql());
            }
        }
        $arrSale = $mishare_from -> field('id,count(*) as shareCount,cid,saleSourceUid')->group('cid,saleSourceUid')->select();
        foreach ($arrSale as $value){
            $shareCount = $value['shareCount'];
            $cid = $value['cid'];
            $saleSourceUid = $value['saleSourceUid'];
            $id = $value['id'];
            if($saleSourceUid){
                //销售员分享数量+1
                $result = R("StatisTics/checkSaleSource", array($saleSourceUid, $cid));
                if ($result) {
                    $statiInfo['uid'] = $saleSourceUid;
                    $statiInfo['cid'] = $cid;
                    $salesource_statistics->add($statiInfo);
                }
                $salesource_statistics->where(['cid' => $cid, 'uid' => $saleSourceUid])->setField('shareCount',$shareCount);
                log::write('销售分享详情_'.$id.':'.$salesource_statistics->getLastSql());
            }
        }

    }

    public function sharViewNum(){
        Session::switchCustomer(0);
        $mishare_from = M('mishare_from');
        $user_statistics = M("user_statistics");
        $miu_statistics = M("miu_statistics");
        $salesource_statistics = M("salesource_statistics");
        $quan_user = M("quan_user");
        $arr = $mishare_from -> field('id,uId,sum(viewCount) as viewCount,sum(viewUv) as viewUv,cid')->group('cid,uId')->select();
        log::write('分享浏览信息:'.json_encode($arr));
        foreach ($arr as $key=>$value){
            $uid = $value['uId'];
            $viewCount = $value['viewCount'];
            $viewUv = $value['viewUv'];
            $cid = $value['cid'];
            $saleSourceUid = $value['saleSourceUid'];
            $id = $value['id'];
            if ($uid) {
                $result = R("StatisTics/checkUser", array($uid, $cid));
                if ($result) {
                    $statiInfo['uid'] = $uid;
                    $statiInfo['cid'] = $cid;
                    $user_statistics->add($statiInfo);
                }
                $data['sharePv'] = $viewCount;
                $data['shareUv'] = $viewUv;
                $user_statistics->where(['cid' => $cid, 'uid' => $uid])->save($data);
                log::write('普通用户分享浏览详情_'.$id.':'.$user_statistics->getLastSql());
            }
            //查询是否为注册好友,如果为注册好友 则给分享人注册好友身份分享数量+1
            $where['b.cId'] = array('eq', $cid);
            $where['a.uId'] = array('eq', $uid);
            $where['a.deleted'] = array('eq', 0);
            $userInfo = $quan_user->alias('a')->where($where)->join('wx_miyouquan as b on a.qid=b.id')->field('qid')->find();
            if (!empty($userInfo['qid']) && $uid) {
                $result = R("StatisTics/checkMiU", array($uid, $cid));
                if ($result) {
                    $data['uid'] = $uid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                /** 5.添加密友分享总次数*/
                $data['sharePv'] = $viewCount;
                $data['shareUv'] = $viewUv;
                $miu_statistics->where(['uid' => $uid, 'cid' => $cid])->setField($data);
                log::write('注册好友分享浏览详情_'.$id.':'.$miu_statistics->getLastSql());
            }

        }
        $arrSale = $mishare_from -> field('id,sum(viewCount) as viewCount,sum(viewUv) as viewUv,cid,saleSourceUid')->group('cid,saleSourceUid')->select();
        foreach ($arrSale as $key=>$value) {
            $viewCount = $value['viewCount'];
            $viewUv = $value['viewUv'];
            $cid = $value['cid'];
            $saleSourceUid = $value['saleSourceUid'];
            $id = $value['id'];
            if($saleSourceUid){
                //销售员分享数量+1
                $result = R("StatisTics/checkSaleSource", array($saleSourceUid, $cid));
                if ($result) {
                    $statiInfo['uid'] = $saleSourceUid;
                    $statiInfo['cid'] = $cid;
                    $salesource_statistics->add($statiInfo);
                }
                $data['sharePv'] = $viewCount;
                $data['shareUv'] = $viewUv;
                $salesource_statistics->where(['cid' => $cid, 'uid' => $saleSourceUid])->setField($data);
                log::write('销售分享浏览详情_'.$id.':'.$salesource_statistics->getLastSql());
            }
        }

    }

    public function orderStatisPush(){
        Session::switchCustomer(0);
        $order = M('module_product_order');
        $where['status'] = array('in','submission,ok,delivering,delivered');
        $orderInfo = $order->where($where)->select();
        $redis = new RedisAPI();
        foreach ($orderInfo as $key=>$value){
            $redis->rPush('orderSuccess_log',$value['id']);
        }
    }
    public function orderStatisPop(){
        Session::switchCustomer(0);
        $orderModel = M('module_product_order');
        $miu_statistics = M('miu_statistics');
        $saleSource_statistics = M('salesource_statistics');
        $ProductOrderModel = M("");
        $redis = new RedisAPI();
        $max = $redis->lLen("orderSuccess_log");
        $arr = $redis->LRANGE("orderSuccess_log",0,-1);
        $count = 0;
        while ($count < $max) {
            $count++;
            $oid = $redis->lPop("orderSuccess_log");
            if ($oid == 'nil' || !isset($oid)) {
                continue;
            }
            $module = 'order';
            $moduleId = $oid;
            $orderInfo = $orderModel->where(['id' => $oid])->field('qId,uId,miUid,refereeUid,parentRefereeUid,price,saleSource,fromCustomerId,type,points')->find();
            $price = $orderInfo['price'];
            $miUid = $orderInfo['miUid'];
            $referrrUid = $orderInfo['refereeUid'];
            $parentRefereree = $orderInfo['parentRefereeUid'];
            $saleSource = $orderInfo['saleSource'];
            $cid = $orderInfo['fromCustomerId'];
            $uId = $orderInfo['uId'];
            $qId = $orderInfo['qId'];
            $orderType = $orderInfo['type'];
            $points = $orderInfo['points'];
            if ( $orderType == 'buy' ){
                $countField = 'buyOrderCount';
                $priceField = 'buyOrderPrice';
            }elseif($orderType == 'form'){
                $countField = 'formOrderCount';
                $priceField = 'formOrderPrice';
            }elseif ($orderType == 'point'){
                $countField = 'pointOrderCount';
                $priceField = 'pointOrderPoint';
                $price = $points;
            }
            $ProductOrderModel->startTrans();
            if($miUid){         //注册好友添加订单数量
                $res = self::checkMiU($miUid,$cid);
                if($res){
                    $data['uid'] = $miUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($referrrUid){    //推荐人添加订单数量
                $res = self::checkMiU($referrrUid,$cid);
                if($res){
                    $data['uid'] = $referrrUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($parentRefereree){           //上级推荐人添加订单数量
                $res = self::checkMiU($parentRefereree,$cid);
                if($res){
                    $data['uid'] = $parentRefereree;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("上级推荐人添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($saleSource){                //销售员添加订单数量
                $res = self::checkSaleSource($saleSource,$cid);
                if($res){
                    $data['uid'] = $saleSource;
                    $data['cid'] = $cid;
                    $saleSource_statistics->add($data);
                }
                $query = "UPDATE wx_salesource_statistics SET $countField = $countField + 1 WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("销售员添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if($qId){
                $query = "UPDATE wx_miyouquan SET $countField = $countField + 1 WHERE cid = $cid AND id  = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈添加订单数量错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }

            if(($orderInfo['price'] || $orderInfo['points']) > 0  &&  $miUid){   //注册好友添加订单金额数量
                $res = self::checkMiU($miUid,$cid);
                if($res){
                    $data['uid'] = $miUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $miUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("注册好友添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $referrrUid){   //推荐人添加订单金额数量
                $res = self::checkMiU($referrrUid,$cid);
                if($res){
                    $data['uid'] = $referrrUid;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $referrrUid";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("推荐人添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $parentRefereree){      //上级推荐人添加订单金额数量
                $res = self::checkMiU($parentRefereree,$cid);
                if($res){
                    $data['uid'] = $parentRefereree;
                    $data['cid'] = $cid;
                    $miu_statistics->add($data);
                }
                $query = "UPDATE wx_miu_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $parentRefereree";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("级推荐人添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $saleSource){    //销售员添加订单金额数量
                $res = self::checkSaleSource($saleSource,$cid);
                if($res){
                    $data['uid'] = $saleSource;
                    $data['cid'] = $cid;
                    $saleSource_statistics->add($data);
                }
                $query = "UPDATE wx_salesource_statistics SET $priceField = $priceField + $price WHERE cid = $cid AND uid  = $saleSource";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("销售员添加订单金额数量:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            if(($orderInfo['price'] || $orderInfo['points'])  &&  $qId){
                $query = "UPDATE wx_miyouquan SET $priceField = $priceField + $price WHERE cid = $cid AND id  = $qId";
                $result = $ProductOrderModel->query($query);
                if ($result === false) {
                    Log::write("营销圈添加订单金额错误:".$ProductOrderModel->getLastSql());
                    $ProductOrderModel->rollback();
                    self::statisStatus($module,$moduleId,$orderType,'fail',$cid);
                    continue;
                }
            }
            $ProductOrderModel->commit();
            self::statisStatus($module,$moduleId,$orderType,'success',$cid);
        }
    }


    public function shareDataMove(){
        Session::switchCustomer(0);
        $mishare_from = M('mishare_from');
        $mishare_visit = M('mishare_visit');
        $arr = $mishare_from->where('visitId is not null')->field('visitId,saleSourceUid')->select();
        foreach ($arr as $value){
            $visitId = $value['visitId'];
            $saleSourceUid = $value['saleSourceUid'];
            $mishare_visit->where(['visitId' => $visitId])->setField('saleSourceUid',$saleSourceUid);
        }

    }




    /**
     * 更新菜单
     */
      public function module_group(){
          Session::switchCustomer(0);
          $role = M("role");
          $roleId = $role->where(['englishRole' => 'business'])->field('cid,id')->select();
          foreach ($roleId as $v){
              $cid = $v['cid'];
              $roleId = $v['id'];
              $sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($cid, '282', $roleId),($cid, '283', $roleId),($cid, '284', $roleId),($cid, '285', $roleId),($cid, '286', $roleId)";
              M()->query($sql1);
          }
      }

    public function posterMove($isWx=1){
        $count = ($isWx == 1) ? WX_TABLE_COUNT : TEST_TABLE_COUNT;
        Session::switchCustomer(0);
        $poster = M("poster");
        for ($i = 1; $i < $count; $i++) {
            $sql_addCol = "select * from wx_". $i ."_module_mall_store";
            $arr = M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();
            header("Content-type: text/html; charset=utf-8");
            echo $lastSql_addCol . '<br />';
            echo '<br />';
            if(empty($arr) || empty($arr[0]['qrcodeBack'])){
                continue;
            }
            $data['posterName'] = '原默认海报';
            $data['posterBack'] = $arr[0]['qrcodeBack'];
            $data['qrcodeLocation'] = $arr[0]['qrcodeLocation'];
            $data['qrcodeSize'] = $arr[0]['qrcodeSize'];
            $data['isJoinQuan'] = 1;
            $data['module'] = 'community';
            $data['moduleId'] = '';
            $data['status'] = 1;
            $data['cid'] = $i;
            $data['creatTime'] = date('Y-m-d H:i:s');
            $data['updateTime'] = date('Y-m-d H:i:s');
            $data['deleted'] = 0;
            $posterId = $poster->add($data);
            $lastSql_addCol = $poster->getLastSql();
            echo $lastSql_addCol . '<br />';
            echo '<br />';
            $sql_addCol = "update wx_module_user_poster set posterId = ".$posterId." where cId = " . $i ." and posterid is null";
            M()->query($sql_addCol);
            $lastSql_addCol = M()->getLastSql();
            echo $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

    public function myqJoinPidMove(){
        header("Content-type: text/html; charset=utf-8");
        Session::switchCustomer(0);
        $productModel = M("module_product");
        $miyouquan = M("miyouquan");
        $sql = "select id, name ,joinPid  from wx_miyouquan where  joinPid is not null and joinPid !=0 ";
        $arr = M()->query($sql);
//        [{"pid":"","productName":"","rankId":"","name":""}]
        foreach ($arr as $key=>$value){
            $data = array();
            $productName = $productModel->where(['id' => $value['joinPid']])->getField('name');
            $data[0]['productName'] = $productName;
            $data[0]['pid'] = $value['joinPid'];
            $data[0]['rankId'] = '';
            $data[0]['name'] = '';
            $data = json_encode($data);
            $miyouquan->where(['id' => $value['id']])->setField('joinPid', $data);
            $lastSql_addCol = $miyouquan->getLastSql();
            echo $lastSql_addCol . '<br />';
            echo '<br />';
        }
    }

}
